package com.sunstar.club.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库加密util
 *
 * @Author: Shylo Sun
 * @Project: track-club
 * @Date: 2024/2/14 19:24
 */
public class DruidEncryptUtil {
    private static String publicKey;
    private static String privateKey;

    /**
     * 生成公钥和私钥
     */
    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512); // 生成公钥和私钥
            privateKey = keyPair[0];
            publicKey = keyPair[1];
            System.out.println("privateKey: " + privateKey);
            System.out.println("publicKey: " + publicKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加密
     *
     * @param plainText
     * @return
     * @throws Exception
     */
    public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("encrypt: " + encrypt);
        return encrypt;
    }

    /**
     * 解密
     *
     * @param cipherText
     * @return
     * @throws Exception
     */
    public static String decrypt(String cipherText) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey, cipherText);
        System.out.println("decrypt: " + decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("qq351603943");
        System.out.println("encrypt: " + encrypt);
    }

}
